package com.example.mybatis.controller;

import com.example.mybatis.mapper.UserMapper;
import com.example.mybatis.model.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * Copyright(C), 2020-2021, AmbroseCdMeng
 * FileName:    UserController
 * Author:      AmbroseCdMeng
 * Date:        2021/1/2914:56
 * Description: User 控制类操作数据 API
 * History:
 * <author>     <time>      <version>       <desc>
 * 作者姓名     修改时间        版本号           描述
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserMapper userMapper;

    @RequestMapping("/querybyid")
    User queryById(int id){
        return userMapper.queryById(id);
    }

    @RequestMapping("/")
    List<User> queryAll(){
        return userMapper.queryAll();
    }

    @RequestMapping("/add")
    int add(User user){
        return userMapper.add(user);
    }

    @RequestMapping("/updatebyid")
    int updateById(User user){
        return userMapper.updateById(user);
    }

    @RequestMapping("/deletebyid")
    int deleteById(int id){
        return userMapper.delById(id);
    }

    /**
     * 分页逻辑控制器
     */

    // @RequestMapping("/listall")
//    public String listCategory1(Model model,
//                               @RequestParam(value = "start", defaultValue = "0") int start,
//                               @RequestParam(value = "size", defaultValue = "20") int size
//    ) throws Exception{
//        /* 这种写法是在 controller 中的 */
//        PageHelper.startPage(start, size, "id desc");
//        List<User> users = userMapper.queryAll();
//        PageInfo<User> page = new PageInfo<>(users);
//        model.addAttribute("page", page);
//        return "list";
//    }
    @RequestMapping("/listall")
    public ModelAndView listCategory(Model model,
                                     @RequestParam(value = "start", defaultValue = "0") int start,
                                     @RequestParam(value = "size", defaultValue = "20") int size
    )throws Exception{
        /* 这种才是在 restcontroller 中 */
        PageHelper.startPage(start, size, "id desc");
        List<User> users = userMapper.queryAll();
        PageInfo<User> page = new PageInfo<>(users);
        model.addAttribute("page", page);
        ModelAndView mv = new ModelAndView("list"); // 页面写在这里
        mv.addObject(model);
        return mv;
    }
}
